import 'package:enya_app_upgrade/app_info.dart';
import 'package:enya_app_upgrade/app_upgrade_style.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'dart:io';

import 'enya_app_upgrade_platform_interface.dart';

class EnyaAppUpgrade {
  Widget _buildProgressBar(double progress, AppUpgradeStyle style) {
    if (style.progressBuilder != null) {
      return style.progressBuilder!(progress);
    }

    return Padding(
      padding: style.progressBarPadding,
      child: ClipRRect(
        borderRadius: BorderRadius.circular(style.progressBarBorderRadius),
        child: SizedBox(
          height: style.progressBarHeight,
          child: LinearProgressIndicator(
            value: progress,
            backgroundColor: style.progressBarBackgroundColor,
            valueColor: AlwaysStoppedAnimation<Color>(style.progressBarColor),
          ),
        ),
      ),
    );
  }

  Widget createDialog(
    String title,
    String content,
    String cancelText,
    String confirmText,
    Function() onCancel,
    Function(Function(double progress) onProgress) onConfirm, {
    AppUpgradeStyle style = const AppUpgradeStyle(),
    String appStoreId = '',
    bool forceUpdate = false,
    String version = '',
  }) {
    double? _progress;
    bool _isDownloading = false;

    return StatefulBuilder(
      builder: (context, setState) {
        void _handleConfirm() async {
          // 跳转 App Store
          if (Platform.isIOS) {
            if (context.mounted && !forceUpdate) {
              Navigator.of(context).pop();
            }
            toAppStore(appStoreId);
            return;
          }

          //启动安装
          final apkPath = await getApkDownloadPath(version);
          final file = File(apkPath);
          if (await file.exists()) {
            if (context.mounted && !forceUpdate) {
              Navigator.of(context).pop();
            }
            await installAppForAndroid(apkPath);
            return;
          }

          // 开始下载
          setState(() {
            _isDownloading = true;
          });

          try {
            await onConfirm((progress) async {
              setState(() {
                _progress = progress;
              });

              if (progress >= 1.0) {
                //刷新ui
                setState(() {
                  _isDownloading = false;
                  _progress = null;
                });

                //启动安装
                final apkPath = await getApkDownloadPath(version);
                final file = File(apkPath);
                if (await file.exists()) {
                  if (context.mounted && !forceUpdate) {
                    Navigator.of(context).pop();
                  }
                  await installAppForAndroid(apkPath);
                } else {
                  if (kDebugMode) {
                    print('APK file not found at path: $apkPath');
                  }
                }
              }
            });
          } catch (e) {
            setState(() {
              _isDownloading = false;
              _progress = null;
            });
            rethrow;
          }
        }

        return WillPopScope(
          onWillPop: () async => !forceUpdate,
          child: Center(
            child: Material(
              type: MaterialType.transparency,
              child: Container(
                margin: style.margin,
                constraints: BoxConstraints(maxHeight: style.maxHeight),
                decoration: BoxDecoration(
                  color: style.backgroundColor,
                  borderRadius: BorderRadius.circular(style.borderRadius),
                ),
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    const SizedBox(height: 24),
                    Text(title, style: style.titleStyle),
                    Flexible(
                      child: Padding(
                        padding: const EdgeInsets.symmetric(
                          vertical: 24,
                          horizontal: 24,
                        ),
                        child: SingleChildScrollView(
                          physics: const BouncingScrollPhysics(),
                          child: Text(
                            content,
                            style: style.contentStyle,
                            textAlign: TextAlign.center,
                          ),
                        ),
                      ),
                    ),
                    Stack(
                      children: [
                        // 进度条层
                        AnimatedOpacity(
                          opacity: _progress != null ? 1.0 : 0.0,
                          duration: const Duration(milliseconds: 200),
                          child: Container(
                            height: style.buttonHeight,
                            padding: const EdgeInsets.symmetric(horizontal: 24),
                            child: Row(
                              children: [
                                Expanded(
                                  child:
                                      _buildProgressBar(_progress ?? 0, style),
                                ),
                                const SizedBox(width: 12),
                                Text(
                                  '${((_progress ?? 0) * 100).toInt()}%',
                                  style: style.progressTextStyle,
                                ),
                              ],
                            ),
                          ),
                        ),
                        // 按钮层
                        AnimatedOpacity(
                          opacity: !_isDownloading ? 1.0 : 0.0,
                          duration: const Duration(milliseconds: 200),
                          child: Container(
                            decoration: BoxDecoration(
                              border: Border(
                                top: BorderSide(color: style.dividerColor),
                              ),
                            ),
                            child: forceUpdate
                                ? InkWell(
                                    onTap:
                                        !_isDownloading ? _handleConfirm : null,
                                    child: Container(
                                      height: style.buttonHeight,
                                      alignment: Alignment.center,
                                      child: Text(
                                        confirmText,
                                        style: style.confirmTextStyle,
                                      ),
                                    ),
                                  )
                                : Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      Expanded(
                                        child: InkWell(
                                          onTap: onCancel,
                                          child: Container(
                                            height: style.buttonHeight,
                                            alignment: Alignment.center,
                                            decoration: BoxDecoration(
                                              border: Border(
                                                right: BorderSide(
                                                    color: style.dividerColor),
                                              ),
                                            ),
                                            child: Text(
                                              cancelText,
                                              style: style.cancelTextStyle,
                                            ),
                                          ),
                                        ),
                                      ),
                                      Expanded(
                                        child: InkWell(
                                          onTap: !_isDownloading
                                              ? _handleConfirm
                                              : null,
                                          child: Container(
                                            height: style.buttonHeight,
                                            alignment: Alignment.center,
                                            child: Text(
                                              confirmText,
                                              style: style.confirmTextStyle,
                                            ),
                                          ),
                                        ),
                                      ),
                                    ],
                                  ),
                          ),
                        ),
                      ],
                    ),
                  ],
                ),
              ),
            ),
          ),
        );
      },
    );
  }

  /// 跳转 App Store
  Future<void> toAppStore(String appId) async {
    return EnyaAppUpgradePlatform.instance.toAppStore(appId);
  }

  /// 获取下载好的 apk 完整地址
  Future<String> getApkDownloadPath(String version) async {
    return EnyaAppUpgradePlatform.instance.getApkDownloadPath(version);
  }

  /// 安装 apk
  Future<void> installAppForAndroid(String path) async {
    return EnyaAppUpgradePlatform.instance.installAppForAndroid(path);
  }

  /// 获取当前应用的信息
  Future<AppInfo> getAppInfo() async {
    return EnyaAppUpgradePlatform.instance.getAppInfo();
  }
}
